import java.util.PriorityQueue;

class MyTask implements Comparable<MyTask>{
    private Runnable task;
    private long time;

    public MyTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    public Runnable getTask() {
        return task;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time-o.time);
    }
}

class MyTimer{
    private PriorityQueue<MyTask>queue=new PriorityQueue<>();
    Object lock=new Object();

    public void schedule(Runnable myTask,long time){
        synchronized (lock){
         MyTask task=new MyTask(myTask,System.currentTimeMillis()+time);
         queue.offer(task);
         lock.notify();
        }
    }

    public MyTimer() {
        Thread thread=new Thread(()->{
            while (true){
                        try {
                            synchronized (lock){
                            while (queue.isEmpty()){
                            lock.wait();
                            }
                            MyTask myTask=queue.peek();
                            if(myTask.getTime()>System.currentTimeMillis()){
                                lock.wait(myTask.getTime()-System.currentTimeMillis());
                            }else {
                             myTask.getTask().run();
                                queue.poll();
                            }
                            }
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
            }
        });
        thread.start();
    }
}
public class CreateTimer1 {
    public static void main(String[] args) {
     MyTimer myTimer=new MyTimer();
     myTimer.schedule(new Runnable() {
         @Override
         public void run() {
             System.out.println("我是任务1");
         }
     },1000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是任务2");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是任务3");
            }
        },3000);
    }
}
